/*
 * logon_sessmgr.cpp
 *
 *  Created on: Dec 16, 2013
 *      Author: killerg
 */

#include "auth_deps.h"
#include "logonsess.h"
#include "auth_cfg.h"
#include "auth.h"
#include "auth_mgr.h"

#include "share/msg.h"

bool logon_session_t::send_msg(la::AMsg* &msg) {
    return g_auth.logonsess_mgr->send_msg(this, msg);
}

void logon_session_t::update() {
}
void logon_session_t::on_connect() {
    UTIL_LOG(I, "on connect \n");
}
void logon_session_t::on_disconnect() {
	UTIL_LOG(I, "on disconnect \n");
}

void handle_lrequest(logon_session_t* sess, la::LMsg* msg) {
    auto &request = msg->request();
    int64_t logonsessid = sess->_sessid;
    int64_t sessid = request.sessid();
    string mc = request.mc();

    g_auth.authmgr->auth(
    		to_json(request.request()),
    		[logonsessid, sessid, mc](result_t res, const account_t& account, const Json::Value& data){
		++g_auth.authmgr->authed_ps;
		auto sess = g_auth.logonsess_mgr->connmgr.map_id.get(logonsessid);
		if (NULL == sess)
			return;

		if (res == Ok) {
			string sdata = to_str(data);
			g_auth.authmgr->onactive(mc, account.platform, [logonsessid, sessid, account, sdata](time_t active){
				auto sess = g_auth.logonsess_mgr->connmgr.map_id.get(logonsessid);
				if (NULL == sess)
					return;

				CREATE_LA_AMSG(AResponse, response);
				response->set_sessid(sessid);
				response->set_playerid(account.playerid);
				response->set_account(account.account);
				response->set_active_time(active);
				response->set_plat(account.platform);
				response->set_data(sdata);
				response->set_result(co::ELAE_Ok);
				sess->send_msg(___msg);
			});
		} else {
			CREATE_LA_AMSG(AResponse, response);
			response->set_sessid(sessid);
			switch (res) {
			case Exist:
				response->set_result(co::ELAE_Exist);
				break;
			case Noexist:
				response->set_result(co::ELAE_NotExist);
				break;
			case AuthFail:
				response->set_result(co::ELAE_PasswdErr);
				break;
			default:
				response->set_result(co::ELAE_TmpErr);
				break;
			}

			sess->send_msg(___msg);
		}
	});
}

bool logonsess_mgr_t::init() {
    bool ret = base::init(
            g_auth.cfg->ListenLogonIp.c_str(),
            g_auth.cfg->ListenLogonPort,
            1,
            -1,
            -1,
            0x0fffffff,
            false
            );
    if (!ret) {
        UTIL_LOG(I, "listening for logon at %s:%d failed",
                g_cfg->ListenLogonIp.c_str(),
                g_cfg->ListenLogonPort);
        return false;
    }

    UTIL_LOG(I, "listening for logon at %s:%d",
            g_cfg->ListenLogonIp.c_str(),
            g_cfg->ListenLogonPort);

    ret = ret && base::reg(la::ID_LRequest, handle_lrequest);
    return ret;
}
